package com.example.administrator.pandanotes;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.litepal.crud.DataSupport;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    //变量***********************************************************************
    User theUser = null;
    private TextView tVUserName = null;
    private List<Note> noteList = new ArrayList<>();//笔记数据
    private ListView NoteListView = null;          //笔记列表
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化******************************************************************
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        tVUserName = (TextView) findViewById(R.id.tVUserName);
        NoteListView = (ListView)findViewById(R.id.lVNote);
        initNotes();
        final NoteAdapter noteAdapter = new NoteAdapter(MainActivity.this,R.layout.note_item,noteList);
        NoteListView.setAdapter(noteAdapter);
        try {
            FileReader r = new FileReader(Environment.getExternalStorageDirectory() + "/pandanotescookies.txt");
            BufferedReader reader = new BufferedReader(r);
            String id = reader.readLine();
            Log.d("UserName:",id);
            if(id != null && (!id.equals(""))){
                List<User> users = DataSupport.where("user_id = ?",id).find(User.class);
                theUser = users.get(0);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
         if(theUser.getUser_name()!=null)   //已经设置好了名字
        {
            tVUserName.setText(theUser.getUser_name()+",欢迎您");
        }
        else                               //没有设置好名字
        {
            tVUserName.setText(theUser.getUser_id()+",欢迎您");
        }
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Snackbar.make(view, "没啥功能,别点了...", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                Intent intent = new Intent(MainActivity.this,NoteAddActivity.class);
                startActivity(intent);
            }
        });
        //事件*******************************************************************
        NoteListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {//点击事件
                 Note note = noteList.get(position);
                Intent intent = new Intent(MainActivity.this,NoteUpdateActivity.class);
                intent.putExtra("note",note);
                startActivity(intent);
            }
        });
        NoteListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, final View view, int position, final long id) {
                /********显示对话框**********/
                AlertDialog.Builder normalDialog =
                        new AlertDialog.Builder(MainActivity.this);
                normalDialog.setIcon(R.drawable.delete);
                normalDialog.setTitle(R.string.confirm_del);
                normalDialog.setMessage(R.string.are_your_sure);
                normalDialog.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        TextView textView = (TextView) view.findViewById(R.id.tVNoteDate);
                        String string = textView.getText().toString();
                        int i = DataSupport.deleteAll(Note.class,"str_date=?",string);
                        if(i!=0)Toast.makeText(MainActivity.this, "已删除", Toast.LENGTH_SHORT).show();
                        else Toast.makeText(MainActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                        Log.d("删除条数：",String.valueOf(i));
                        Log.d("删除书籍类：",String.valueOf(id));
                        initNotes();
                        noteAdapter.notifyDataSetChanged();
                    }
                });
                normalDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                normalDialog.show();

                return true;
            }
        });
    }
    //菜单***********************************************************************
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {       //菜单初始化
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {   //菜单项被选中事件
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if(id==R.id.menu_main)
        {
           //Toast.makeText(getBaseContext(),"EditEvent",Toast.LENGTH_LONG).show();
        }
        else if (id==R.id.menu_user)
        {
            Intent intent3 = new Intent(MainActivity.this,UserActivity.class);//跳转用户页面
            intent3.putExtra("theUser",theUser); //传当前用户
            startActivity(intent3);
        }
        else if(id==R.id.menu_class)
        {
            Intent intent = new Intent(MainActivity.this,BookClassActivity.class);//跳转书籍类管理页面
            intent.putExtra("theUser",theUser); //传当前用户
            startActivity(intent);
        }
        else if (id==R.id.menu_book)
        {
            Intent intent1 = new Intent(MainActivity.this,BooksActivity.class);//跳转书管理页面
            intent1.putExtra("theUser",theUser); //传当前用户
            startActivity(intent1);
        }
        else if(id==R.id.menu_about)
        {
            Intent intent2 = new Intent(MainActivity.this,AboutActivity.class);//跳转关于页面
            startActivity(intent2);
        }
        else if(id==R.id.menu_count)//跳转至笔记统计页面
        {
            Intent intent4 = new Intent(MainActivity.this,NoteInfoActivity.class);//跳转关于页面
            startActivity(intent4);
        }
        else if (id==R.id.menu_logout)
        {
            Intent intent4 = new Intent(MainActivity.this,LoginActivity.class);//跳转退出页面
            startActivity(intent4);
            finish();
        }
        return true;
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click();
            return true;
            //调用双击退出函数
        }
        return super.onKeyDown(keyCode, event);
    }
    /**
     * 双击退出函数
     */
    private static Boolean isESC = false;

    private void exitBy2Click() {
        Timer tExit ;
        if (!isESC) {
            isESC = true; // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            tExit = new Timer();
            tExit.schedule(new TimerTask() {
                @Override
                public void run() {
                    isESC = false; // 取消退出
                }
            }, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            System.exit(0);
        }
    }
    private void initNotes()
    {
        List<Note> notes = DataSupport.findAll(Note.class); //得到笔记类表所有数据
        noteList.clear();
        for(Note note:notes)                                //每个数据项进行ListView的映射
        {
            noteList.add(note);                            //添加所有note
            Log.d("书名",note.getBook_name());
            Log.d("笔记对应书",note.getBooks()+"");
            Log.d("笔记内容",note.getNote_content());
            Log.d("笔记日期Note",note.getStr_date()+"");
            Log.d("笔记日期Str",note.getStr_date());
        }
    }
}

